package com.putong35.common.httprequest.retrofit;

import android.util.Log;

import com.putong35.common.httprequest.retrofit.converter.HttpError;
import com.putong35.common.httprequest.OnFailureListener;
import com.putong35.common.httprequest.OnSuccessListener;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HttpCommonCallback<T> implements Callback<T> {
    public static final String TAG = HttpCommonCallback.class.getSimpleName();
    private OnSuccessListener<T> successListener;
    private OnFailureListener failureListener;

    public HttpCommonCallback(OnSuccessListener<T> successListener, OnFailureListener failureListener) {
        this.successListener = successListener;
        this.failureListener = failureListener;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        Log.d(TAG, "onResponse: ");
        T data = response.body();
        if (data != null) {
            if (successListener != null) {
                successListener.onSuccess(1, "成功", data, null);
            }


        } else {
            if (failureListener != null) {
                // TODO 具体的服务器错误code
                failureListener.onFailure(-1, "数据为空");
            }
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable throwable) {
        throwable.printStackTrace();
        int code = -1;
        if (throwable instanceof HttpError) {
            HttpError error = ((HttpError) throwable);
            if (error.body instanceof ResponseData) {
                ResponseData data = ((ResponseData) error.body);
                code = data.code;
            }

        }
        Log.d(TAG, "onFailure: " + throwable.getMessage());
        if (failureListener != null) {
            failureListener.onFailure(code, throwable.getMessage());
        }
    }
}
